import { defineComponent } from 'vue';
import {
  complaintList,
  complaintDetail,
  getComplaint,
  dReportDetail
} from '@/api/home';
import SheltV2 from '../../common/SheltV2';
import Echarts from '@/components/Echarts';
import { ElIcon, ElImage, ElTooltip } from 'element-plus';
import { ArrowRight } from '@element-plus/icons-vue';
import './index.less';
import SearchRow from '../SearchRow';
import Detail from '../Detail';
import { dateFormatter } from '@/utils';

export default defineComponent({
  name: 'Complaint',
  setup() {
    const { VITE_STATIC_URL } = import.meta.env;
    const detailRef = ref();
    const itemDetail = reactive({
      list: [],
      tab: 1
    });
    const itemDetailRef = ref();
    const reportDetailRef = ref();

    const data = reactive({
      search: {
        year: undefined
      },
      list: [
        {
          key: 'year',
          type: 'popup_year',
          title: '日期选择',
          icon: 'calendar',
          placeholder: '请选择'
        }
      ]
    }) as AnyObject;
    const itemData = reactive({
      search: {
        year: undefined
      },
      list: [
        {
          key: 'year',
          type: 'popup',
          title: '日期选择',
          icon: 'calendar',
          placeholder: '请选择'
        }
      ],
      tab: {
        key: '',
        list: [
          { label: '问题类型', value: 1 },
          { label: '产品类型', value: 2 }
        ]
      }
    }) as AnyObject;

    const reportData = reactive({
      search: {
        month: [new Date().getFullYear(), new Date().getMonth() + 1]
      },
      list: [
        {
          key: 'month',
          type: 'popup',
          title: '日期选择',
          icon: 'calendar',
          placeholder: '请选择'
        }
      ]
    }) as AnyObject;

    const detail = ref({}) as AnyObject;
    const tableDetail = [
      { title: '考核月份', key: 'month' },
      { title: '目标客诉', key: 'target' },
      { title: '实际客诉', key: 'reality' },
      {
        title: '环比降幅',
        key: 'rate',
        render(key: string) {
          key + '%';
        }
      }
    ];
    const itemTableDetail = ref([
      { title: '问题类型(大类)', key: 'name' },
      { title: '客服单数', key: 'number' }
    ]);
    const reportDableDetail = [
      { title: '投诉日期', key: 'date' },
      { title: '标题', key: 'title' },
      { title: '小组成员', key: 'name' },
      {
        title: '详情',
        key: 'url',
        render(key: string) {
          return (
            <a href={key} target="_blank">
              详情
            </a>
          );
        }
      }
    ];
    const option = ref({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      color: ['#4a74ea', '#eb833c', '#ffc61c'],
      legend: {
        left: '0%',
        data: ['目标客诉', '实际客诉', '降幅率'],
        icon: 'circle',
        itemGap: 30,
        itemWidth: 10
      },
      grid: {
        left: 50
        // right: '100%',
        // top: "10%",
        // bottom: '90%'
      },
      xAxis: [
        {
          type: 'category',
          data: [],
          axisPointer: {
            type: 'shadow'
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
        }
      ],

      yAxis: [
        {
          type: 'value'
        },
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '目标客诉',
          type: 'bar',

          // barWidth: 8,
          data: []
        },
        {
          name: '实际客诉',
          type: 'bar',

          // barWidth: 8,
          data: []
        },
        {
          name: '降幅率',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          lineStyle: {
            width: 3
          },
          symbol: 'none',
          tooltip: {
            valueFormatter: function (value: string) {
              return value + '%';
            }
          },
          data: []
        }
      ],
      dataZoom: {
        type: 'inside',
        start: 50,
        end: 100,
        zoomOnMouseWheel: false,
        moveOnMouseMove: true,
        moveOnMouseWheel: true,
        minValueSpan: 4,
        throttle: 50
      }
    }) as any;
    const detailSlots = ref({
      detail: () => <SearchRow onSearch={complaintChartList} datekey='year' data={data} />
    });

    getComplaint().then((res) => {
      detail.value = res.data;
    });

    const viewDetail = () => {
      detailRef.value.show = true;
    };

    const complaintChartList = () => {
      const year = dateFormatter(data.search.year);

      complaintList({ year }).then((res) => {
        const sdata = {
          target: [],
          reality: [],
          rate: [],
          month: []
        } as AnyObject;
        res.data.list.forEach((_item: AnyObject) => {
          sdata.target.push(_item.target);
          sdata.reality.push(_item.reality);
          sdata.rate.push(_item.rate);
          sdata.month.push(_item.month);
        });
        option.value.series[0].data = sdata.target;
        option.value.series[1].data = sdata.reality;
        option.value.series[2].data = sdata.rate;
        option.value.xAxis[0].data = sdata.month;
      });
    };
    const viewReport = () => {
      reportDetailRef.value.show = true;
    };
    const viewLiDetail = (val: AnyObject) => {
      itemData.search.month = val.month.split('/');
      itemDetailRef.value.show = true;
    };
    const handleTab = (tab: any) => {
      itemDetail.tab = tab;
      itemTableDetail.value[0].title =
        itemDetail.tab == 1 ? '问题类型(大类)' : '产品名称';
      console.log(itemData.search.month);
      const month = dateFormatter(itemData.search.month);
      complaintDetail({ month }).then((res: AnyObject) => {
        itemDetail.list =
          res.data?.[tab == 1 ? 'deviceTypeInfoData' : 'issueTypeInfoData'];
      });
    };
    const searchDetail = (item: any) => {
      itemData.search.month = item.month;
      handleTab(itemDetail.tab);
    };
    complaintChartList();

    return () => (
      <>
        <SheltV2
          title="客诉情况"
          more="查看详情"
          v-slots={detailSlots.value}
          onViewDetail={viewDetail}
          question="<div><p>【该数据每日02:00更新一次】</p><p>客诉情况是汇总海外业务工单和电商/海外线下工单的客诉工单，本月的实际客诉、目标客诉和相较上月同期降幅。</p></div>"
        >
          <Echarts aspectRatio="1/1" option={option.value} />
          <div class="complaint flex-start">
            <div class="complaint_item">
              <div class="title">本月目标数量</div>
              <div class="num">{detail.value?.target_number}</div>
            </div>
            <div class="complaint_item">
              <div class="title">本月实际数量</div>
              <div class="num">{detail.value?.number}</div>
              <div class="fill">
                较上月同期降幅：<span>{detail.value?.decrease}%</span>
              </div>
            </div>
            <div class="complaint_item">
              <div class="flex-start">
                <div class="title">本月8D报告</div>
                <ElTooltip
                  effect="light"
                  placement="top"
                  content="8D报告是指因批量客诉事件、生产异常事故而编制的系统性的解决方案报告。"
                >
                  <ElImage
                    style={{ width: '15px' }}
                    src={`${VITE_STATIC_URL}/tcpl/question.png`}
                  ></ElImage>
                </ElTooltip>
              </div>
              <div style={{ color: '#de0404' }} class="num">
                {detail.value?.report}
              </div>
              <div
                class="flex-start hover-color fill detail"
                onClick={viewReport}
              >
                查看详情
                <ElIcon>
                  <ArrowRight />
                </ElIcon>
              </div>
            </div>
          </div>
        </SheltV2>
        <Detail
          title="客诉情况"
          datakey='year'
          ref={detailRef}
          filterDetail={data}
          tableDetail={tableDetail}
          requestApi={complaintList}
          onViewLiDetail={viewLiDetail}
        />
        <Detail
          title="客诉情况"
          ref={itemDetailRef}
          filterDetail={itemData}
          tableDetail={itemTableDetail.value}
          onHandleTab={handleTab}
          onSearch={searchDetail}
          list={itemDetail.list}
        />
        <Detail
          title="8D报告"
          ref={reportDetailRef}
          filterDetail={reportData}
          tableDetail={reportDableDetail}
          requestApi={dReportDetail}
        />
      </>
    );
  }
});
